package com.hyh.eblog.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.deser.impl.MergingSettableBeanProperty;
import com.hyh.eblog.common.lang.Result;
import com.hyh.eblog.dto.UserLoginParam;
import com.hyh.eblog.dto.UserRegisterParam;
import com.hyh.eblog.entity.User;
import com.hyh.eblog.mapper.UserMapper;
import com.hyh.eblog.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyh.eblog.shiro.AccountProfile;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Summerday
 * @since 2020-10-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    UserMapper userMapper;

    @Override
    public Result register(UserRegisterParam registerParam) {
        int count = this.count(new QueryWrapper<User>()
                .eq("email", registerParam.getEmail())
                .or()
                .eq("username", registerParam.getUsername())
        );
        if(count > 0) return Result.fail("用户名或邮箱已被占用");
        User user = new User();
        user.setUsername(registerParam.getUsername());
        user.setEmail(registerParam.getEmail());
        user.setPassword(SecureUtil.md5(registerParam.getPassword()));
        user.setCreated(new Date());
        user.setPoint(0);
        user.setVipLevel(0);
        user.setCommentCount(0);
        user.setAvatar("/res/images/avatar/0.jpg");
        user.setPostCount(0);
        this.save(user);
        return Result.success("注册成功");
    }

    @Override
    public Result login(UserLoginParam loginParam) {
        String username = loginParam.getUsername();
        String password = loginParam.getPassword();
        UsernamePasswordToken token = new UsernamePasswordToken(username, SecureUtil.md5(password));
        try{
            SecurityUtils.getSubject().login(token);
        }catch (AuthenticationException e){
            if(e instanceof UnknownAccountException) return Result.fail("用户不存在");
            else if(e instanceof LockedAccountException) return Result.fail("用户被禁用");
            else if(e instanceof IncorrectCredentialsException) return Result.fail("密码错误");
            else return Result.fail("用户认证失败");
        }
        return Result.success("登录成功");
    }

    @Override
    public AccountProfile login(String username, String password) {

        User user = this.getOne(new QueryWrapper<User>().eq("username", username));
        if(user == null){
            throw new UnknownAccountException();
        }
        if(!user.getPassword().equals(password)){
            throw new IncorrectCredentialsException();
        }
        // 设置最后登录时间
        user.setLasted(new Date());
        this.updateById(user);

        AccountProfile profile = new AccountProfile();
        BeanUtils.copyProperties(user,profile);
        return profile;
    }
}
